const BASE_URL = "http://10.138.43.59:3005";

// 刷新 token 方法
async function refreshToken() {
	const refresh_token = uni.getStorageSync("refresh_token");

	if (!refresh_token) {
		return Promise.reject("无效的 refresh_token");
	}

	try {
		const res = await uni.request({
			url: `${BASE_URL}/user/admin/refresh`,
			method: "GET",
			data: {
				refresh_token
			}
		});

		if (res.statusCode === 200 || res.statusCode === 201) {
			// 更新 token
			uni.setStorageSync("access_token", res.data.access_token);
			uni.setStorageSync("refresh_token", res.data.refresh_token);
			return res.data.access_token;
		} else {
			uni.showToast({
				title: "刷新 token 失败",
				icon: "none"
			})
			throw new Error("刷新 token 失败");
		}
	} catch (error) {
		uni.showToast({
			title: "刷新 token 失败",
			icon: "none"
		})
		console.error("刷新 token 失败:", error);
		uni.removeStorageSync("access_token");
		uni.removeStorageSync("refresh_token");

		// 跳转到登录页
		uni.reLaunch({
			url: "/pages/login/login"
		});
		return Promise.reject(error);
	}
}

// 封装请求方法
export const request = (config = {}, retry = true) => {
	let {
		url,
		method = "GET",
		header = {},
		data = {}
	} = config;
	url = BASE_URL + url;

	// 获取 access_token 并添加到请求头
	const accessToken = uni.getStorageSync("access_token");
	if (accessToken) {
		header.authorization = "Bearer " + accessToken;
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url,
			header,
			method,
			data,
			success: async (res) => {
				// 处理 401 (token 失效) 的情况
				if (res.statusCode === 401 && retry) {
					try {
						const newToken = await refreshToken();
						if (newToken) {
							// 重新请求
							return resolve(request({
								...config,
								retry: false
							}));
						}
					} catch (refreshError) {
						return reject(refreshError);
					}
				}

				// 成功请求
				if (res.statusCode === 200 || res.statusCode === 201) {
					resolve(res.data);
				} else {
					uni.showToast({
						title: res.data.data || "系统繁忙，请稍后再试",
						icon: "none",
						position: "top",
					});
					reject(res.data.data);
				}
			},
			fail: (err) => {
				uni.showToast({
					title: "网络异常，请稍后重试",
					icon: "none",
					position: "top",
				});
				reject(err);
			},
		});
	});
};